﻿using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Model.Cloud.Dashboard.Statistics;
using DiLe.Mes.Model.Common.Abnormal.Entity;
using DiLe.Mes.Model.Common.Equipment.Entity.Manage;
using DiLe.Mes.Model.Local.Abnormal.Entity;
using DiLe.Mes.Service.Common.Equipment.Info;
using DiLe.Mes.Service.Dto;
using MapleLeaf.Core.EventBus;
using MapleLeaf.Core.Serilog;

namespace DiLe.Mes.Cloud.Expansion {
    /// <summary>
    /// 
    /// </summary>
    public class DataReceiveAlarm {
        private readonly static ISqlSugarClient _masterDb = SqlSugarHelper.MasterDb;
        private readonly static ISqlSugarClient _cloudDb = SqlSugarHelper.CloudDb;



        private static readonly string[] separator = [","];


        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static void SaveData(MessageModel model) {
            if (model.SendMsg.IsNullOrEmpty()) {
                return;
            }
            switch (model.MsgSign) {
                case "AlarmInfo":
                    _ = ReveiveAlarmInfo(model);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 设备报警信息
        /// </summary>
        /// <returns></returns>
        private static bool ReveiveAlarmInfo(MessageModel model) {
            string id = Guid.NewGuid().ToString();
            try {
                SerilogLogHelper.WriteSystemLog($"设备报警信息开始接收=>{id}：{model.SendMsg}");

                var models = JsonConvert.DeserializeObject<List<AlarmInfoEntity>>(model.SendMsg!);
                if (models == null && models.None()) {
                    return false;
                }
                var signs = models!.ConvertAll(x => x.DeviceNo!);
                var inserts = SaveAlarmInfo(signs, models, model.AppId);
                if (inserts.None()) {
                    return false;
                }
                _ = _cloudDb.Deleteable<AlarmInfoStatisticsEntity>(p => p.FactoryId == model.AppId).ExecuteCommand();

                var res = _cloudDb.Insertable(inserts).ExecuteCommand();
                SerilogLogHelper.WriteSystemLog($"设备报警信息接收完成=>{id}");
                return res > 0;
            } catch (Exception ex) {
                var str = $"设备报警信息接收完成失败=>{id}：{ex.Message}";
                SerilogLogHelper.WriteSystemErrorLog(str);
                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="signs"></param>
        /// <param name="list"></param>
        /// <param name="factoryId"></param>
        private static List<AlarmInfoStatisticsEntity> SaveAlarmInfo(List<string> signs, List<AlarmInfoEntity> list, long? factoryId) {
            var day = DateTime.Now.Date;
            // _equipmentManage3

            var infos = GetEquipmentInfoModelListBySign(signs, factoryId).GetAwaiter().GetResult();
            var typeids = infos.ConvertAll(x => x.EquipmentTypeId).ToList();
            //设备报警信息
            var aaInfoList = _masterDb.Queryable<AbnormalAlarmRuleEntity>().Where(x => typeids.Contains(x.EquipmentTypeId)).ToList();

            var inserts = new List<AlarmInfoStatisticsEntity>();
            foreach (var item in list) {
                var info = infos.FirstOrDefault(p => p.EquipmentSign == item.DeviceNo);
                if (info == null) {
                    continue;
                }
                if (item.AlarmData.IsNullOrEmpty()) {
                    continue;
                }

                var rules = aaInfoList.Where(p => p.EquipmentTypeId == info.EquipmentTypeId).ToList();
                if (rules.None()) {
                    continue;
                }
                var abnormaltype = rules.FirstOrDefault(p => p.AlarmName == item.AlarmData);
                if (abnormaltype == null) {
                    continue;
                }
                var m = new AlarmInfoStatisticsEntity() {
                    EquipmentCode = info.EquipmentCode,
                    EquipmentName = info.EquipmentName,
                    AbnormalContent = $"{abnormaltype.AlarmDescription}",
                    AbnormalInfo = item.AlarmData,
                    AbnormalLevel = abnormaltype.AlarmLevel,
                    AbnormalDate = item.AlarmDate ?? "",
                    StartAbnormalTime = item.StartAlarmTime ?? DateTime.Now,
                    EndAbnormalTime = item.EndAlarmTime,
                    FactoryId = factoryId,
                };
                inserts.Add(m);

            }
            return inserts;

        }

        /// <summary>
        /// 根据设备标记获取设备信息
        /// </summary>
        /// <returns></returns>
        private static async Task<List<EquipmentInfoModel>> GetEquipmentInfoModelListBySign(List<string> signlist, long? factoryId) {
            var list = await _masterDb.Queryable<EquipmentRegisterEntity>()
                                 .LeftJoin<EquipmentInfoEntity>((r, i) => r.EquipmentInfoId == i.Id)
                                 .LeftJoin<EquipmentTypeEntity>((r, i, t) => i.TypeId == t.Id)
                                 .Where((r, i, t) => signlist.Contains(r.EquipmentSign) && i.FactoryId == factoryId)
                                 .Select((r, i, t) => new EquipmentInfoModel {
                                     EquipmentId = i.Id,
                                     EquipmentCode = i.Code,
                                     EquipmentTypeId = i.TypeId,
                                     EquipmentTypeName = t.Name,
                                     Specification = i.Specification,
                                     EquipmentName = i.Name,
                                     EquipmentSign = r.EquipmentSign,
                                     DayStandardHour = i.DayStandardHour ?? 0,
                                     NightStandardHour = i.NightStandardHour ?? 0
                                 })
                                 .ToListAsync();
            return list;
        }
    }
}
